/*
 *The code is written by NaLi, All rights reserved.
 */
package com.nali.dal.statement.function.formatter;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.nali.dal.statement.function.AbstractDataHandler;
import com.nali.dal.statement.function.FunctionArgument;
import com.nali.dal.statement.function.FunctionException;

/**
 * @author gavin Created on 2011-4-26
 */
@Component
public class ToNumber extends AbstractDataHandler<Number> {

	@Override
	public Number handle(List<Object> argList) throws FunctionException {
		Number radix = null;
		if (argList.size() >= 1) {
			Object value = argList.get(0);
			if (value instanceof Number) {
				return (Number) argList.get(0);
			} else {
				String valueStr = (String) argList.get(0);
				if (argList.size() >= 2) {
					radix = (Number) argList.get(1);
				}
				if (!StringUtils.isEmpty(valueStr)) {
					if (radix == null) {
						return Long.valueOf(valueStr.trim());
					} else {
						return Long.valueOf(valueStr.trim(), radix.intValue());
					}
				}
			}
		}
		return null;
	}

	@Override
	public void validate(List<FunctionArgument> arguments) throws FunctionException {
		checkSize(arguments, 1, 2);
	}

}
